package com.guos.json;

import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import lombok.Data;


/**
 * @author 郭帅
 * @date 2023/9/27 15:54
 */

@Data
public class Test {

    public static Object extractFieldValue(String jsonStr, String fieldPath) {
        if (StringUtils.isEmpty(jsonStr) || StringUtils.isEmpty(fieldPath)) {
            return null;
        }
        JSONObject jsonObject = null;
        try {
            jsonObject = JSON.parseObject(jsonStr);
        } catch (Exception e) {
//            log.error("WidgetsParamUtils.extractFieldValue json parseObject error, fieldPath:{}, jsonStr:\n{}", fieldPath, jsonStr);
        }
        if (jsonObject == null) {
            return null;
        }
        String[] fieldNames = fieldPath.split("\\.");
        if (fieldNames.length == 0) {
            return null;
        }
        JSONObject currentObject = jsonObject;
        for (int i = 0; i < fieldNames.length - 1; i++) {
            currentObject = currentObject.getJSONObject(fieldNames[i]);
            if (currentObject == null) {
                // Field not found
                return null;
            }
        }
        // Extract the Boolean field value
        return currentObject.get(fieldNames[fieldNames.length - 1]);
    }

    public static void main(String[] args) {
        String jsonString = "{\"extra_info\":{\"ads_engagebar_info\":{\"live_trailer_engagebar_enable\":true}}}";
        // Extract the value of "live_trailer_engagebar_enable" field
        Object fieldValue = extractFieldValue(jsonString, "extra_info.ads_engagebar_info.live_trailer_engagebar_enable");
    }
}
